/*
 * Copyright 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.layer8apps;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.InputStream;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

public class ConnectionManager {
    private static ConnectionManager instance = null;
    private DefaultHttpClient client;

    private ConnectionManager() {
        client = new DefaultHttpClient();
    }

    // Public method that will be invoked from other classes
    public static ConnectionManager getInstance() {
        if (instance == null) {
            instance = new ConnectionManager();
        }
        return instance;
    }

    // Public method that will be invoked from other classes
    public static ConnectionManager newConnection() {
        instance = new ConnectionManager();
        return instance;
    }

    public Bitmap getBitmap(String url) {
        Bitmap bitmap = null;
        HttpTask httpTask = new HttpTask();
        String params[] = {"bmp", url};
        httpTask.execute(params);
        while (!httpTask.done) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                Log.e("ERRORLOG", e.getMessage());
            }
        }
        bitmap = httpTask.bitmap;
        return bitmap;
    }

    public String getData(String url) {
        String tempData = null;
        try {
            HttpGet get = new HttpGet(url);
            HttpResponse response = client.execute(get);
            tempData = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
            return tempData;
        } catch (Exception e) {
            Log.e("ERRORLOG", e.getMessage());
            return null;
        }
    }

    public String postData(String url, List<NameValuePair> params) {
        String tempData = null;
        try {
            HttpPost post = new HttpPost(url);
            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
            post.setEntity(ent);
            HttpResponse response = client.execute(post);
            HttpEntity resEnt = response.getEntity();
            if (resEnt != null) {
                tempData = EntityUtils.toString(resEnt);
                return tempData;
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    public List<NameValuePair> buildParameters(List<String[]> args) {
        List<NameValuePair> parameters = new LinkedList<NameValuePair>();
        try {
            for (String[] e : args) {
                parameters.add(new BasicNameValuePair(e[0].toString(), e[1].toString()));
            }
            return parameters;
        } catch (Exception e) {
            return null;
        }
    }

    private class HttpTask extends AsyncTask<String, Void, String> {

        public boolean done = false;
        public Bitmap bitmap = null;
        public String data;

        @Override
        protected String doInBackground(String... params) {
            done = false;
            try {
                String type = params[0];
                if (type.equals("bmp")) {
                    URL url = new URL(params[1]);
                    InputStream is = url.openStream();
                    bitmap = BitmapFactory.decodeStream(is);
                } else if (type.equals("movie")) {

                }
            } catch (Exception e) {
                Log.e("ERRORLOG", e.getMessage());
            }
            done = true;
            return null;
        }
    }
}
